<?php
namespace Cyfy\Modules\Users;

/**
 * Class for administration of permissions.
 */
class Permissions extends \Cyfy\Translatable
{
    /**
     * Returns list of modules with their permission rules, which can be enabled for users in groups.
     * @retun string HTML content
     */
    static public function administration()
	{
        if(!\Cyfy\Cyfy ::  permission("Users", "groups and permissions")){
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
		// add js and css
		\Cyfy\Cyfy ::  JavaScript(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/Users/permissions.js"), "file", "header");
		\Cyfy\Cyfy ::  CSS(\Cyfy\Cyfy ::  getSourcePath("Cyfy/Modules/Users/permissions.css"), "file", "header");
	
		// permission form
		$output = "<form method=\"get\" id=\"userAdminPermissionsForm\" onsubmit=\"savePermissions(this);return false;\">\n";
		
        // list of groups without Administrators
        $groups =  array_slice(Groups :: getAll(true, true), 1, null, true);
        
        // css - color table headers
        $css = "";
        
		// all none buttons
		$buttons = array(self :: t(820));
        $groupsNames = array();
		foreach($groups as $gid => $g){
            if($g["color"]){
                $css .= ".admin-permissions th[title={$g["short"]}] {  background-color: #{$g["color"]} } \n";
            }
            $groupsNames[] = $g["short"];
			$buttons[] = "<input type=\"submit\" value=\"" . self :: t(830) . "\" gid=\"{$gid}\" class=\"userAdminPermissionsAll\" /><br /><input type=\"submit\" gid=\"{$gid}\" value=\"" .  self :: t(840) . "\" class=\"userAdminPermissionsNone\" />";
		}
        
        // add css to header
		\Cyfy\Template :: addHeader("<style>" . $css . "</style>");
        
		$table = new \Cyfy\Modules\Objects\Table("admin-permissions admin-permissions-all-none", "all-none-buttons");
		$table -> row($buttons);
		$table -> classes(array(0=>"title"));
		$allNoneButtons = $table -> show();
		// add all none buttons
		$output .= $allNoneButtons;
		
		// get current settings
		$current = array();
		$result = \dibi :: query("SELECT * FROM [:cyfy:Users-groups-permissions]");
		foreach($result as $p)
		{
			$current[$p["gid"]][$p["module"]][$p["permission"]] = true;
		}
		
        
        // header
        $header = array_merge(array(self :: t(850)), $groupsNames);
        // td classes
        $classes = array(0=>'title');
        
        // going trough modules
        foreach(\Cyfy\Modules :: getInstalled() as $module)
        {
			$info = \Cyfy\Modules :: getInfo($module);
			$permissions = "";
			
			// if no permissions
			if(count($info["permissions"]) == 0){
				continue;
			}
			
			// table
			$table = new \Cyfy\Modules\Objects\Table("admin-permissions");
			$table -> header($header);
			$table -> classes($classes);
			// permissions in one module
			foreach($info["permissions"] as $permission)
			{
				$list = array($permission);
				// for each group do
				foreach($groups as $gid => $group)
				{
					$checked = ($current[$gid][$module][$permission]) ? "checked=\"checked\"" : "";
					$list[] = "<input type=\"checkbox\" class=\"groupPermission_$gid\" name=\"groupPermission[$gid][$module][$permission]\" value=\"1\" {$checked}/>";
				}
				$table -> row($list);
			}
			
            $name = $module;
            // fetch name
            $class = '\Cyfy\Modules\\' . $module . '\Module';
            if(class_exists($class)){
                $name = ($class :: getName()) ?: $module;
            }
            
			$permissions = $table -> show();
            
			$output .= <<<OUTPUT
<h3>{$name}</h3>			
			
			$permissions
OUTPUT;
			
		
		}
		// add buttons
		$output .= $allNoneButtons;
		$output .= "<div class=\"form-buttons\"><input type=\"submit\" value=\"" . self :: t(870)  . "\" /> </div>";
		return $output;
	
	}
	
    /**
     * Saves permissions. 
     * Must be called while posting value $_POST["groupPermission"][$groupID][$module][$permission] = true;
     */
	static public function ajaxSave()
	{
        if(!\Cyfy\Cyfy ::  permission("Users", "groups and permissions")){
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
		if(is_array($_POST["groupPermission"]))
		{
			// delete old
			\dibi :: query("TRUNCATE TABLE [:cyfy:Users-groups-permissions]");
			// for each group
			foreach($_POST["groupPermission"] as $gid => $modules)
			{
				foreach($modules as $module => $permissions)
				{
					foreach($permissions as $permission => $val)
					{
                        $values = array('gid' => $gid, 'module' => $module, 'permission' => $permission);
						\dibi :: query("INSERT INTO [:cyfy:Users-groups-permissions] %v", $values);
					}		
				}
			}
			\Cyfy\Message :: set(self :: t(880));
		}
	}
	
    
}
